import 'package:core/mvi/mvi_view_model_extension.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:feature_main/controller/home_tab_state.dart';
import 'package:feature_main/controller/tab_view_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_it/get_it.dart';
import 'package:ui/loading.dart';

class MviHomeTabPage extends StatefulWidget {
  const MviHomeTabPage({super.key});

  @override
  State<MviHomeTabPage> createState() => _MviHomeTabPageState();
}

class _MviHomeTabPageState extends State<MviHomeTabPage>
    with AutomaticKeepAliveClientMixin {
  bool _isInitialized = false;

  final TabViewModel viewModel = Get.put(
    TabViewModel(
      bannerUseCase: GetIt.I.get(),
      homeArticleUseCase: GetIt.I.get(),
    ),
  );

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    viewModel.handleSideEffect(context, (effect) {
      if (effect is InitFinishedEffect) {
        debugPrint('init finished effect param:${effect.param}');
      } else if (effect is ShowLoadingEffect) {
        Loading.show('Loading');
      } else if (effect is HideLoadingEffect) {
        Loading.dismiss();
      }
    });

    // // 只在第一次初始化时发送InitEvent
    WidgetsBinding.instance.addPostFrameCallback((_) {
      debugPrint('send event----');
      if (!_isInitialized && viewModel.initialized) {
        _isInitialized = true;
        viewModel.sendEvent(InitEvent());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用，因为使用了AutomaticKeepAliveClientMixin
    return SafeArea(
      child: GetBuilder(
        init: viewModel,
        builder: (viewModel) {
          return Obx(() {
            final state = viewModel.state;

            if (state.isLoading) {
              return CircularProgressIndicator().center();
            }

            return Column(
              children: [
                SizedBox(height: 10.h),
                OutlinedButton(onPressed: () {
                  viewModel.sendEvent(NewEvent(value: 'ss'));
                }, child: Text('send new event')),
                OutlinedButton(
                  onPressed: () {
                    viewModel.sendEvent(TestSendEvent(param: "param here"));
                  },
                  child: Text('send event'),
                ).paddingTop(10.h),
                OutlinedButton(
                  onPressed: () {
                    viewModel.sendEvent(TestLoadingEvent());
                  },
                  child: Text('send loading event'),
                ).paddingTop(5.h),
                Row(
                  children: state.banners.asMap().entries.map((entry) {
                    final value = entry.value;
                    return Text(value.title);
                  }).toList(),
                ).paddingTop(10.h),
              ],
            );
          });
        },
      ),
    );
  }
}
